package com.shsmi.jc.seed.service.impl;

import cn.hutool.core.util.StrUtil;
import com.shsmi.jc.seed.common.ErrorCode;
import com.shsmi.jc.seed.entity.SystemUser;
import com.shsmi.jc.seed.exception.MyException;
import com.shsmi.jc.seed.repository.SystemUserRepository;
import com.shsmi.jc.seed.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private SystemUserRepository repository;

    @Override
    public SystemUser getByUsername(String username) {
        return repository.findFirstByUsername(username);
    }

    @Override
    public SystemUser register(SystemUser user)  throws MyException {
        if (StrUtil.hasBlank(user.getUsername()) || StrUtil.hasBlank(user.getLoginPassword())) {
            throw new MyException(ErrorCode.AUTH_USERNAME_CAN_NOT_BE_NULL,"用户名不能为空");
        }
        if(repository.findFirstByUsername(user.getUsername())!=null){
            throw new MyException(ErrorCode.USER_USERNAME_ALREADY_EXIST,"用户名已存在");
        }
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setAvatarUrl("");
        user.setLoginPassword(passwordEncoder.encode(user.getLoginPassword()));
        return repository.save(user);
    }
}
